import json
import requests
from robot import tonken_Inquire, send
import datetime
import time

# 获取时间戳范围
today = datetime.date.today()
today_time = int(time.mktime(today.timetuple()) * 1000)
now_time = time.time()
roles = '测试'
ProcessCode = 'PROC-8C56C171-2EEF-4E34-8D4F-F0FAA8B122CC'


# 获取角色列表
def get_roles():
    url = 'https://oapi.dingtalk.com/topapi/role/list?access_token=' + tonken_Inquire
    data = {
        "size": "20",
        "offset": "0"
    }
    Response = requests.post(url=url, data=json.dumps(data)).json()
    # print(Response)
    for i in range(0, len(Response['result']['list'])):
        for j in range(0, len(Response['result']['list'][i]['roles'])):
            # print(Response['result']['list'][1]['roles'][j]['name'])
            if Response['result']['list'][1]['roles'][j]['name'] == roles:
                return Response['result']['list'][i]['roles'][j]['id']


get_roles()


# 获取员工的userId
def get_userId():
    url = 'https://oapi.dingtalk.com/topapi/role/simplelist?access_token=' + tonken_Inquire
    data = {
        "size": 20,
        "offset": 0,
        # "role_id": 3197479725  # 角色ID
        "role_id": get_roles()
    }
    Response = requests.post(url=url, data=json.dumps(data)).json()
    # print(Response['result']['list'])
    return Response['result']['list']


get_userId = get_userId()


# print(get_userId)


def Inquire(i):
    processCode = ProcessCode  # 要查询的审批流程id
    startTime = today_time
    endTime = int(round(now_time * 1000))
    userIds = get_userId
    url = 'https://api.dingtalk.com/v1.0/workflow/processes/instanceIds/query'
    headers = {
        'Host': 'api.dingtalk.com',
        'x-acs-dingtalk-access-token': tonken_Inquire,
        'Content-Type': 'application/json',

    }
    data = {
        "processCode": processCode,
        "startTime": startTime,
        "endTime": endTime,
        "nextToken": 0,
        "maxResults": 1,
        "userIds": "['" + userIds[i]['userid'] + "']",
    }
    # print(i)
    # print(userIds[i]['name'])
    # print(userIds[i]['userid'])
    Response = requests.post(url=url, headers=headers, data=json.dumps(data)).json()
    # print(Response)
    if not Response['result']['list']:
        print(userIds[i]['name'] + "未经提交研发日志,即将发送机器人提醒")
        send(userIds[i]['userid'], userIds[i]['name'])
    else:
        print(userIds[i]['name'] + "已经提交研发日志")


if __name__ == '__main__':
    for i in range(0, len(get_userId)):
        Inquire(i)
